<?php

namespace app\common\model;

use Jenssegers\Agent\Agent;
use think\Model;
use think\Request;

/**
 * 会员模型
 */
class Promotion Extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    // 追加属性
    protected $append = [

    ];

    public static function doPromotion($promotion_id)
    {
        $promotion = Promotion::where('id', $promotion_id)->find();
        $request = Request::instance();
        $ua = $request->header('user-agent');
        if (!empty($promotion) && !empty($promotion->url)) {

            //更新访问数量
            $visited = PromotionRecord::isVisitedToday($promotion['id']);
            if (empty($visited)) {
                $promotion->uv = $promotion->uv +1;

            }
            $promotion->pv = $promotion->pv +1;
            $promotion->save();

            //更新访问记录
            $agent = new Agent();
            if ($agent->isMobile()) {
                $browser  = '-';
                $version = $agent->version($agent->platform());
            } else {
                $browser  = $agent->browser();
                $version = $agent->version($browser);
            }

            $data = [
                'promotion_id' => $promotion['id'],
                'url' => $promotion['url'],
                'ip' => $request->ip(),
                'ua' => $ua,
                'device' => $agent->device(),
                'platform' => $agent->platform(),
                'version' => $version,
                'browser' => $browser,
            ];
            PromotionRecord::create($data);

            header("location:" . $promotion->url);
        } else {
            return false;
        }

    }

}
